import React from 'react'
import { useHistory } from 'react-router-dom'
// ================================================================ Image
import Bcimg from '@img/collect/bcimage.png'
import Logo from '@img/collect/logo.png'
import Image from '@tp/image'
const {$fn} = window
// ===================================================================== Dclare
const getIdInfo = (IdCard) => {
    var reg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
    if(reg.test(IdCard)){
		let sex
        if (parseInt(IdCard.substr(16, 1)) % 2 === 1) {
			sex = '1'
		} else {
			sex = '0'
		}
		var ageDate = new Date()
		var month = ageDate.getMonth() + 1
		var day = ageDate.getDate()
		var age = ageDate.getFullYear() - IdCard.substring(6, 10)
		if (IdCard.substring(10, 12) < month || (IdCard.substring(10, 12) === month && IdCard.substring(12, 14) <= day)) {
			age++
		}
		if (age <= 0) {
			age = 1
		}
		return { sex, age}
	}else{
        return false;
    }
}
const testIdNO = (value) =>{
  var vcity = {
      11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古",
      21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏",
      33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南",
      42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆",
      51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃",
      63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外"
  };

  // 判断是否为空
  let isEmpty = function (card) {
      if (/^\s*$/.test(card) === true) {
          return true;
      }
  }
  //检查号码是否符合规范，包括长度，类型  
  let isCardNo = function (card) {
      if (isEmpty(card)) {
          return true;
      }
      //这个代码表示身份证可以为空
      //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
      var reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/;
      if (reg.test(card) === false) {
          return false;
      }


      return true;
  };

  //取身份证前两位,校验省份  
  let checkProvince = function (card) {
      if (isEmpty(card)) {
          return true;
      }
      var province = card.substr(0, 2);
      if (vcity[province] === undefined) {
          return false;
      }
      return true;
  };

  //检查生日是否正确  
  let checkBirthday = function (card) {
      if (isEmpty(card)) {
          return true;
      }
      var len = card.length;
      //身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字  
      if (len === 15) {
          var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/;
          var arr_data = card.match(re_fifteen);
          var year = arr_data[2];
          var month = arr_data[3];
          var day = arr_data[4];
          var birthday = new Date('19' + year + '/' + month + '/' + day);
          return verifyBirthday('19' + year, month, day, birthday);
      }
      //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X  
      if (len === 18) {
          var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/;
          let arr_data = card.match(re_eighteen);
          let year = arr_data[2];
          let month = arr_data[3];
          let day = arr_data[4];
          let birthday = new Date(year + '/' + month + '/' + day);
          return verifyBirthday(year, month, day, birthday);
      }
      return false;
  };

  //校验日期  
  let verifyBirthday = function (year, month, day, birthday) {
      var now = new Date();
      var now_year = now.getFullYear();
      //年月日是否合理  
      if (birthday.getFullYear() === +year && (birthday.getMonth() + 1) === +month && birthday.getDate() === +day) {
          //判断年份的范围（3岁到100岁之间)  
          var time = now_year - year;
          if (time >= 3 && time <= 200) {
              return true;
          }
          return false;
      }
      return false;
  };

  //校验位的检测  
  let checkParity = function (card) {
      if (isEmpty(card)) {
          return true;
      }
      //15位转18位  
      card = changeFivteenToEighteen(card);
      var len = card.length;
      if (len === 18) {
          var arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
          var arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
          var cardTemp = 0, i, valnum;
          for (i = 0; i < 17; i++) {
              cardTemp += card.substr(i, 1) * arrInt[i];
          }
          valnum = arrCh[cardTemp % 11];
          if (valnum === card.substr(17, 1)) {
              return true;
          }
          return false;
      }
      return false;
  };

  //15位转18位身份证号  
  let changeFivteenToEighteen = function (card) {
      if (isEmpty(card)) {
          return true;
      }
      if (card.length === 15) {
          var arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
          var arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
          var cardTemp = 0, i;
          card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
          for (i = 0; i < 17; i++) {
              cardTemp += card.substr(i, 1) * arrInt[i];
          }
          card += arrCh[cardTemp % 11];
          return card;
      }
      return card;
  };

  //checkCard = function () {
  var card = value;
  //校验长度，类型  
  if (isCardNo(card) === false) {
      //alert('您输入的身份证号码不正确，请重新输入');
      //document.getElementById('card_no').focus;
      return false;
  }
  //检查省份  
  if (checkProvince(card) === false) {
      return false;
  }
  //校验生日  
  if (checkBirthday(card) === false) {
      return false;
  }
  //检验位的检测  
  if (checkParity(card) === false) {
      return false;
  }

  return true;
}
/* --------------------------- View --------------------------- */
const List = ({name,label,model,onClick,value,type, onChanged, key=10000, style, r}) =>{
	return(
		<div className='lh22 w g6 mt5' key={key} style={style}>
			<h6 className='lh25'><span style={{color: 'red'}}> {r ? '*' : ''} </span>{name}</h6>
			<div className='ex h'>
				{
					type ==='select'?
					(label==='usex'?
						<select placeholder='请输入' type='select' className='w h40 r3px bcb' defaultValue={String(value)} style={{border:0,outline:'none',background:'#f7f7f7'}} onChange={(e)=>{
							model.current[label] = e.target.value
						}}>
							<option value='1'>男</option>
							<option value='0'>女</option>
						</select>
						:
						<select placeholder='请输入' type='select' className='w h40 r3px bcb' defaultValue={String(value)} style={{border:0,outline:'none',background:'#f7f7f7'}} onChange={(e)=>{
							model.current[label] = e.target.value
						}}>
							<option value='0'>身份证</option>
							<option value='1'>护照</option>
							<option value='2'>军官证</option>
							<option value='3'>港澳居民通行证</option>
							<option value='4'>台湾居民通行证</option>
							<option value='5'>其它</option>
						</select>
					)
					:<input placeholder='请输入' className='w h40 r3px bcb pl5' style={{background:'#f7f7f7'}} defaultValue={value} onChange={(e)=>{
						model.current[label] = e.target.value
						onClick?.(e.target.value)
						onChanged && onChanged(e.target.value)
						// var reg = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/
					}} />
				}
			</div>
		</div>
	)
}
const Index = ( ) => {
	const save = $fn.local('userDatas')
	const model = React.useRef({
		usex:'1',
		utype:'0',
		...save
	})
	const [ key, setKey ] = React.useState( 0 )
	const { reid } = window.$fn.query()
	const history = useHistory( )
	const [ back, setBack] = React.useState( save )
	const [ index, setIndex] = React.useState( 10000 )
	return (
		<>
			<div className='wh plr10 fv' style={{background:`url(${Bcimg}) no-repeat top center/100%`, paddingTop:'18%'}}>
				<div className='ex rel'>
					<div className='abs_full bcf r8px plr10 oys' key={key} >
						<div className='mt10'>
							<List name='姓名' model={model} label='uname' value={back.uname} r={1} />
							<List name='证件类型' model={model} label='utype' type='select' value={back.utype} />
							<List name='证件号' model={model} label='ucardno' value={back.ucardno} r={1} onChanged={ value => {
								const rs = getIdInfo(value)
								if(rs){
									setBack( data =>{
										const param = { ...model.current, ...data, ucardno:value, usex:rs.sex, uage:rs.age }
										model.current = param
										return param
									})
									setIndex(index => index = index + 1)
								}
							}} />
							<React.Fragment key={index} >
								<List name='性别' model={model} label='usex' type='select' value={back.usex} style={{marginRight:'10px'}} />
								<List name='年龄' model={model} label='uage' value={back.uage} />
							</React.Fragment>
							<List name='手机号' model={model} label='uphone' value={back.uphone} r={1} />
							<List name='备注' model={model} label='remark' value={back.remark} r={1} />
						</div>
						<div className='fxmc ptb10'>
							<button className='cf r8px h40 f15' style={{width:'120px', background:'#1eaec6'}} onClick={()=>{
								const { uname, ucardno, uphone, utype, remark } = model.current
								if(!uname){
									return window.$fn.toast('请输入姓名')
								}
								if(!ucardno){
									return window.$fn.toast('请输入证件号')
								}
								// if (utype === '0' && !(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/g).test(ucardno)) {
								// 	return window.$fn.toast('请输入正确的证件号')
								// }
								if ( +utype ===  0 && !testIdNO(ucardno)) {
									return window.$fn.toast('请输入正确的证件号')
								}
								if(!uphone){
									return window.$fn.toast('请输入手机号')
								}
								if(!(/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/g.test(uphone))){
									return window.$fn.toast('请输入正确的手机号')
								}
								if(!remark){
									return window.$fn.toast('请填写备注信息')
								}
								const fn = $fn.local('userData')
								let { id } = $fn.local('userData')
								if(ucardno !== fn.ucardno ){ id = '' }
								window.$http.post(null,'createUser',{ param:{ area_id:reid, ...model.current, usex: +model.current.usex,  id }, loading:true }).then(data=>{
									$fn.local('userDatas', model.current)
									$fn.local('userData',{ area_id:reid, ...data })
									window.$fn.toast('信息提交成功')
									history.push(`/details`)
								})
							}}>立即提交</button>
							<button className='bcf r8px h40 f15 ml20' style={{width:'120px',color:'#1eaec6', border:'1px solid #1eaec6'}} onClick={data=>{
								$fn.localClear()
								model.current = {}
								if($fn.hasObject(back)){
									for(let i in back){
										back[i] = ''
									}
									setBack({})
								}
								setKey(key => key = key + 1)
							}}>清空</button>
						</div>
					</div>
				</div>
				<footer className='fxmc ptb10'>
					<Image src={Logo} width={100} />
				</footer>
			</div>
		</>
	)
}
export default Index